package com.example.administrator.radarplusfriendsdemo.custom;

import android.content.Context;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.example.administrator.radarplusfriendsdemo.R;
import com.example.administrator.radarplusfriendsdemo.been.EightPointConfig;
import com.example.administrator.radarplusfriendsdemo.been.Info;

import java.util.ArrayList;

/**
 * 雷达容器
 */
public class RadarViewGroup extends ViewGroup {
    private static final String TAG = RadarViewGroup.class.getSimpleName();

    private static final int MAX_LENGTH = 8;//最大数据的个数
    private int mWidth, mHeight;//viewgroup的宽高

    //8个点对应的半径
    float[] radiusRate = new float[8];

    //8个点对应的角度
    double[] angles = new double[8];

    private ArrayList<Info> mDatas = new ArrayList<>();//存储数据的集合

    public RadarViewGroup(Context context) {
        this(context, null);
    }

    public RadarViewGroup(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RadarViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        //初始化8个点对应的半径比例
        for (int i = 0; i < this.radiusRate.length; i++) {
            this.radiusRate[i] = EightPointConfig.RADIUS_RATE[i];
        }
        //初始化8个点对应的默认角度
        for (int i = 0; i < angles.length; i++) {
            angles[i] = EightPointConfig.DEFAULT_ANGLES[i] / 180 * Math.PI;
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //这个的操作主要就是为了防止当子容器的布局参数为wrap_content时，此时显示为全屏的样式
        setMeasuredDimension(measureSize(widthMeasureSpec), measureSize(heightMeasureSpec));
        //测量每个children
        measureChildren(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {

        mWidth = getWidth();
        mHeight = getHeight();
        //接下来就容器中的控件布局，就是让控件放在哪？
        //首先放置雷达扫描图
        View view = findViewById(R.id.rv_radar);
        if (view != null) {
            view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        }
        //如果孩子的个数只有一个,说明只有一个雷达图，所以没有必要进行布局。
        int childCount = getChildCount();
        if(childCount == 1){
            return;
        }
        //然后放置多个自定义的CircleView
        //给所有的孩子布局
        for (int i = 1; i < 1 + mDatas.size() ; i++) {
            View child = getChildAt(i);
            //获得基础半径,中心点
            int baseR = mWidth / 2;
            int centerX = mWidth / 2;
            int centerY = mHeight / 2;
            int left = (int) (centerX + radiusRate[i - 1] * baseR * Math.cos(angles[i - 1]));
            int top = (int) (centerY + radiusRate[i - 1] * baseR * Math.sin(angles[i - 1]));

            //获得圆头像的宽度和高度
            float circleWidth = getResources().getDimension(R.dimen.circleview_widht_height);
            float circleHeight = getResources().getDimension(R.dimen.circleview_widht_height);
            //获得TextView的宽度和高度
            float textViewWidth = getResources().getDimension(R.dimen.textview_width);
            float textViewHeight = getResources().getDimension(R.dimen.textview_height);
            //取圆头像和textView宽度的最大值
            float width = circleWidth > textViewWidth ? circleWidth:textViewWidth;
            //圆头像 + 标题的高度之和作为总的高度
            float height = circleHeight + textViewHeight;

            //对控件进行布局,让控件居中显示
            child.layout((int) (left - width / 2),
                    (int) (top - (height) / 2),
                    (int) (left + width / 2),
                    (int) (top + (height) / 2));
            //设置点击事件
            final int finalI = i;
            child.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(getContext(), "这是第" + finalI + "个数据！", Toast.LENGTH_SHORT).show();
                }
            });
        }

    }

    private int measureSize(int measureSpec) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        } else {
            result = 300;
            if (specMode == MeasureSpec.AT_MOST) {
                result = Math.min(result, specSize);
            }
        }
        return result;
    }

    /**
     * 设置数据
     *
     * @param datas
     */
    public void setDatas(@NonNull ArrayList<Info> datas) {
        //TODO 根据距离排序
        //以后有可能有这样的需求：根据距离来对数据进行排序，以后可以来做。
        if (datas == null) {
            return;
        }
        mDatas.clear();
        //对数据源进行一个筛选
        mDatas.addAll(filterData(datas));
        //根据数据源信息动态添加CircleView
        for (int i = 0; i < mDatas.size(); i++) {
            CircleView circleView = new CircleView(getContext());
            circleView.setInfo(datas.get(i));
            addView(circleView);
        }
    }

    /**
     * 过滤数据
     * @param datas 数据源
     * @return 返回过滤后的数据
     */
    private ArrayList<Info> filterData(ArrayList<Info> datas) {
        ArrayList<Info> mResult = new ArrayList<>();
        if (datas == null){
            return mResult;
        }
        if (datas.size() > MAX_LENGTH){
            for (int i = 0; i < MAX_LENGTH; i++) {
                mResult.add(datas.get(i));
            }
            return mResult;
        }else{
            return datas;
        }
    }

    /**
     * 生成8个头像的角度
     */
    public void changePosition() {

        //8个点对应的角度
        angles = new double[8];
        double[] startAngles = EightPointConfig.START_ANGLES;
        double[] range = EightPointConfig.RANGE;
        for (int i = 0; i < angles.length; i++) {
            angles[i] = (startAngles[i] + range[i] * Math.random()) / 180.0 * Math.PI;
        }

        //重新刷新布局
        requestLayout();
    }
}
